package com.anlogic.sdk.bsp.ui;

import com.anlogic.sdk.bsp.handlers.NewPlatformProjectHandler;
import com.anlogic.sdk.utils.LogUtils;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.apache.logging.log4j.Logger;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.operation.*;
import java.lang.reflect.InvocationTargetException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.core.runtime.CoreException;


public class NewPlatformProjectWizard extends Wizard implements INewWizard {
	private static Logger logger = LogUtils.getLogger(NewPlatformProjectWizard.class);
	
	private NewPlatformProjectWizardPage platformProjWizardPage;
	
	public NewPlatformProjectWizard() {
		super();
		setNeedsProgressMonitor(true);
	}
	
	@Override
	public void addPages() {
		platformProjWizardPage = new NewPlatformProjectWizardPage();
		addPage(platformProjWizardPage);
	}
	
	@Override
	public boolean performFinish() {
		return createPlatformProject() ;
	}
	
	@Override
	public void init(IWorkbench workbench, IStructuredSelection selection) {}
	
	private boolean createPlatformProject() {
		IRunnableWithProgress op = monitor -> {
			try {
				createPlatformProject(monitor);
			} catch (CoreException e) {
				throw new InvocationTargetException(e);
			} finally {
				refreshProject(platformProjWizardPage.getModel().getProjName());
				monitor.done();
			}
		};
		try {
			getContainer().run(true, false, op);
		} catch (InterruptedException e) {
			logger.error("Create Platform Project Error");
			return false;
		} catch (InvocationTargetException e) {
			logger.error("Create Platform Project Failed");
			Throwable realException = e.getTargetException();
			MessageDialog.openError(getShell(), "Error", realException.getMessage());
			return false;
		}
		return true;
	}

	private void createPlatformProject(IProgressMonitor monitor) throws CoreException {
		NewPlatformProjectHandler.newInstance(platformProjWizardPage.getModel()).run(monitor);
	}
	
	public void refreshProject(String projName) {
		try {
			IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projName);
			if (project.exists()) {
				project.refreshLocal(IResource.DEPTH_INFINITE, null);
			}
		} catch (CoreException e) {
			logger.error("Create Platform Project Error while refreshing platform project {}", e.getMessage());
		}
	}
}